<template>
  <div class="table-container">
    <div class="right">
      <div class="header">
        <search-bar
          key="users"
          v-model="queryParams"
          :config="searchColumn"
          @search="handleSearch"
          @searchReset="handleReset"
        />
        <el-button v-hasPermi="['system.role.add']" class="m_96" type="primary" @click="handleUserDialog">
          新增
        </el-button>
      </div>
      <table-page
        width="100%"
        class="user-table"
        :table-data="tableData"
        :table-column="tableColumn"
        :is-index="true"
        :is-selection="false"
        :total="pages.total"
        :page-size="pages.pageSize"
        :current-page="pages.pageNum"
        @sizeChange="handleSizeChange"
        @currentChange="handleCurrentChange"
      />

      <!-- 新增/编辑 -->
      <el-dialog
        width="700px"
        class="app-dialog"
        :title="`${userDialogType}`"
        :visible.sync="userDialogVisible"
        :before-close="handleUserDialogClose"
        :close-on-click-modal="false"
      >
        <div class="container">
          <el-form ref="userEdit" :model="userDialogData" label-position="top">
            <el-form-item
              label="所属系统"
              prop="belongSystem"
              :rules="[{ required: true, message: '请选择所属系统', trigger: 'change' }]"
            >
              <el-select v-model="userDialogData.belongSystem" placeholder="请选择所属系统" style="width: 100%">
                <el-option label="CRM" value="0" />
                <el-option label="劳保" value="1" />
                <el-option label="系统设置" value="2" />
              </el-select>
            </el-form-item>
            <el-form-item
              label="角色名称"
              prop="roleName"
              :rules="[{ required: true, message: '请选择所属系统', trigger: 'change' }]"
            >
              <el-input v-model="userDialogData.roleName" placeholder="请输入角色名称" />
            </el-form-item>
            <el-form-item
              label="状态"
              prop="status"
              :rules="[{ required: true, message: '请选择所属系统', trigger: 'change' }]"
            >
              <el-radio-group v-model="userDialogData.status">
                <el-radio label="0">生效</el-radio>
                <el-radio label="1">失效</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="菜单权限">
              <!-- <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')"
                >展开/折叠</el-checkbox
              >
              <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')"
                >全选/全不选</el-checkbox
              >
              <el-checkbox v-model="form.menuCheckStrictly" @change="handleCheckedTreeConnect($event, 'menu')"
                >父子联动</el-checkbox
              > -->
              <el-tree
                ref="menu"
                v-model="userDialogData.menuIds"
                :default-expanded-keys="defaultExpandedKeys"
                class="tree-border"
                :data="menuOptions"
                show-checkbox
                node-key="id"
                :check-strictly="false"
                :props="defaultProps"
                @check-change="handleTreeCheckChange"
              />
            </el-form-item>
          </el-form>
          <!-- <Form
              ref="userEdit"
              v-model="userDialogData"
              :config="userDialogConfig"
              label-width="80px"
              label-position="top"
            /> -->
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button class="button" @click="handleUserDialogClose">取 消</el-button>
          <el-button class="button" type="primary" @click="handleUserSubmit">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 权限弹窗 -->
      <!-- <el-dialog
      width="40%"
      class="app-dialog"
      title="编辑权限"
      :visible.sync="authDialogVisible"
      :before-close="handleAuthDialogClose"
      :close-on-click-modal="false"
    >
      <div class="container" style="height: 450px; overflow-y: scroll" v-if="authDialogVisible">
        <el-tree
          ref="authTree"
          show-checkbox
          :data="authOptions"
          node-key="name"
          :props="{
            value: 'name',
            label: 'displayName',
            children: 'children',
          }"
          :default-expand-all="true"
          :default-checked-keys="checkedKeys"
          :check-strictly="false"
        />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleAuthDialogClose">取 消</el-button>
        <el-button type="primary" @click="handleAuthSubmit">确 定</el-button>
      </span>
    </el-dialog> -->
    </div>
  </div>
</template>

<script>
import Form from '@/components/Form'
import SearchBar from '@/components/SearchBar'
import TablePage from '@/components/TablePage'
import {
  listRole,
  addRole,
  treeselect,
  updateRole,
  getRole,
  delRole,
  roleMenuTreeselect
} from '@/api/SystemSetting/accounts'
import { parseTime } from '@/utils/ruoyi'
export default {
  name: 'UserSearchTable',
  components: {
    SearchBar,
    TablePage,
    Form
  },
  data() {
    return {
      menuCheckStrictly: true,
      activeTab: 'basicInfo',
      preventMenuFetch: false,
      isAdmin: false,
      filterText: '',
      roleOptions: [],
      menuOptions: [],
      checkedKeys: [],
      queryParams: {},
      selectValue: [],
      deptTree: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      isFetchingRole: false,
      isFetchingMenu: false,
      filterRole(query, item) {
        if (!item || !item.label) {
          return false
        }
        return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1
      },
      searchColumn: [
        { prop: 'roleName', type: 'input', placeholder: '角色名称' },
        {
          prop: 'status',
          type: 'select',
          placeholder: '角色状态',
          options: [
            { label: '生效', value: '0' },
            { label: '失效', value: '1' },
            { label: '休眠', value: '2' }
          ]
        },
        { label: '创建时间', prop: 'createTime', type: 'datetimerange', placeholder: '开始时间', width: '100px' },
        {
          prop: 'search',
          type: 'button',
          policy: ['system.role.query']
        }
      ],
      tableData: [],
      tableColumn: [
        { label: '所属系统', prop: 'belongSystemName' },
        // { label: '用户名', prop: 'userName' },
        { label: '角色名称', prop: 'roleName' },
        { label: '状态', prop: 'statusText' },
        { label: '创建时间', prop: 'createTime' },
        { label: '创建人', prop: 'createBy' },
        {
          label: '操作',
          prop: 'action',
          fixed: 'right',
          type: 'roleButton',
          width: 150,
          buttons: [
            {
              label: '编辑',
              type: 'text',
              method: 'handleEdit',
              color: 'rgba(0, 118, 255, 1)',
              policy: ['system.role.edit'],
              hide: 'roleName',
              hideValue: ['超级管理员']
            },
            {
              label: '删除',
              type: 'text',
              method: 'handleDelete',
              color: '#F37272',
              policy: ['system.role.remove'],
              hide: 'roleName',
              hideValue: ['超级管理员']
            }
          ]
        }
      ],
      userDialogType: '',
      userDialogVisible: false,
      userDialogData: {
        roleName: '',
        roleKey: '',
        roleSort: '',
        belongSystem: '',
        status: '',
        deptIds: [],
        menuIds: [],
        deptCheckStrictly: true,
        menuCheckStrictly: true,
        createBy: ''
      },
      userDialogConfig: [
        {
          label: '所属系统',
          prop: 'belongSystem',
          type: 'select',
          options: [
            { label: 'CRM', value: '0' },
            { label: '劳保', value: '1' },
            { label: '系统设置', value: '2' }
          ],
          rules: [{ required: true, message: '请选择所属系统', trigger: 'change' }]
        },
        {
          label: '角色名称',
          prop: 'roleName',
          type: 'input',
          placeholder: '请输入角色名称',
          rules: [{ required: true, message: '请输入角色名称', trigger: 'blur' }]
        },

        {
          label: '状态',
          prop: 'status',
          type: 'radio',
          options: [
            { label: '生效', value: '0' },
            { label: '失效', value: '1' }
          ],
          rules: [{ required: true, message: '请选择状态', trigger: 'blur' }]
        },
        {
          label: '菜单权限',
          prop: 'menuIds',
          type: 'tree',
          options: this.menuOptions,
          onCheckChange: this.handleTreeCheckChange,
          checkedKeys: this.checkedKeys
          // rules: [{ required: true, message: '请选择状态', trigger: 'blur' }]
        }
      ],

      authDialogVisible: false,
      pages: {
        total: 0,
        pageNum: 1,
        pageSize: 10
      }
    }
  },
  computed: {
    defaultExpandedKeys() {
      return this.menuOptions.map((menu) => menu.id)
    }
  },
  watch: {
    filterText(val) {
      if (this.$refs.orgTree) {
        this.$refs.orgTree.filter(val)
      }
    },
    'userDialogData.belongSystem': function (newSystem) {
      // if (!this.preventMenuFetch) {
      this.getMenuTree(newSystem)
      // }
    }
    // menuOptions(newOptions) {
    //   this.userDialogConfig.find((item) => item.prop === 'menuIds').options = newOptions
    // },
    // checkedKeys(newKeys) {
    //   // 更新 userDialogConfig 中的 checkedKeys
    //   this.userDialogConfig.find((item) => item.prop === 'menuIds').checkedKeys = newKeys
    // }
  },

  async mounted() {
    this.$bus.$off('handleEdit')
    this.$bus.$off('handleAuth')
    this.$bus.$off('handleDelete')
    // 编辑
    this.$bus.$on('handleEdit', async (rows) => {
      try {
        this.userDialogType = '编辑'
        this.userDialogVisible = true
        const roleMenuTreeRes = await roleMenuTreeselect(rows.roleId)
        const role = roleMenuTreeRes.data
        const res = await getRole(rows.roleId)
        const roleDetail = res.data
        this.userDialogData = {
          roleId: roleDetail.roleId,
          roleName: roleDetail.roleName,
          belongSystem: roleDetail.belongSystem,
          status: roleDetail.status,
          deptIds: roleDetail.deptIds || [],
          menuIds: roleDetail.menuIds || [],
          deptCheckStrictly: roleDetail.deptCheckStrictly,
          menuCheckStrictly: roleDetail.menuCheckStrictly,
          createBy: roleDetail.createBy,
          createTime: roleDetail.createTime,
          roleKey: roleDetail.roleKey,
          roleSort: roleDetail.roleSort,
          updateBy: roleDetail.updateBy,
          updateTime: roleDetail.updateTime
        }
        // 获取系统对应的菜单
        await this.getMenuTree(rows.belongSystem)
        this.userDialogData.menuIds = role.checkedKeys
        this.checkedKeys = role.checkedKeys
        this.$nextTick(() => {
          this.$refs.menu.setCheckedKeys(this.checkedKeys) // 设置选中的菜单
        })
        // console.log(this.userDialogData.menuIds, this.checkedKeys, '=666===')
        this.setPsdUsername()
      } catch (error) {}
    })
    // 删除
    this.$bus.$on('handleDelete', (rows) => {
      this.$confirm(`删除后，关联的账号权限将同步删除，确定要删除吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delRole(rows.roleId).then((res) => {
          if (this.pages.total % this.pages.pageSize === 1) {
            const lastpage = (this.pages.total + this.pages.pageSize - 1) / this.pages.pageSize
            if (this.pages.pageNum == lastpage) {
              this.pages.pageNum = this.pages.pageNum - 1
            }
          }
          this.getTableData()
          this.$message({ type: 'success', message: '删除角色成功!' })
        })
      })
    })
  },
  created() {
    this.getTableData()
  },
  beforeDestroy() {
    this.$bus.$off('handleEdit')
    this.$bus.$off('handleAuth')
    this.$bus.$off('handleDelete')
  },
  methods: {
    getTransferTitles(belongSystem, selectedCount) {
      if (!belongSystem) {
        return ['可选菜单', `已选择${selectedCount}项`]
      }
      if (belongSystem === '0') {
        return ['CRM系统', `已选择${selectedCount}项`]
      } else if (belongSystem === '1') {
        return ['劳保系统', `已选择${selectedCount}项`]
      } else if (belongSystem === '2') {
        return ['系统设置', `已选择${selectedCount}项`]
      }
      return ['可选菜单', `已选择${selectedCount}项`]
    },

    handleSearch() {
      if (this.queryParams.createTime && this.queryParams.createTime.length === 2) {
        this.queryParams.params = {
          beginTime: parseTime(this.queryParams.createTime[0], '{y}-{m}-{d} {h}:{i}:{s}'),
          endTime: `${parseTime(this.queryParams.createTime[1], '{y}-{m}-{d}')} 23:59:59`
        }
      } else {
        this.queryParams.params = {}
      }
      delete this.queryParams.createTime
      this.pages.pageNum = 1
      this.getTableData()
    },
    handleReset() {
      this.pages.pageNum = 1
      this.getTableData()
    },
    handleSizeChange(v) {
      this.pages.pageSize = v
      this.pages.pageNum = 1
      this.getTableData()
    },
    handleCurrentChange(v) {
      this.pages.pageNum = v
      this.getTableData()
    },
    handleUserDialog() {
      this.userDialogType = '新增'
      this.userDialogVisible = true
      // 只初始化必要的字段
      this.userDialogData = {
        roleName: '',
        belongSystem: '',
        status: '0',
        deptIds: [],
        menuIds: [],
        deptCheckStrictly: true,
        menuCheckStrictly: true
      }
      if (this.$refs.userEdit) {
        this.$refs.userEdit.resetFields()
      }
      this.roleOptions = []
      this.selectValue = []
      this.preventMenuFetch = false
      this.menuOptions = []
      this.checkedKeys = []
      this.$nextTick(() => {
        this.$refs.menu.setCheckedKeys([]) // 设置菜单的选中状态为空
      })
      this.setPsdUsername()
    },
    handleUserDialogClose() {
      if (this.$refs.userForm) {
        this.$refs.userForm.resetFields()
      }
      this.preventMenuFetch = false
      this.menuOptions = []
      this.selectValue = []
      this.userDialogVisible = false
    },
    setPsdUsername() {
      // const rule = [
      //   { required: true, trigger: 'change', message: '请输入密码' },
      //   { required: true, validator: this.passwordValid, trigger: 'change' }
      // ]
      // const $id = this.userDialogData.id
      // const psd = this.userDialogConfig.find((i) => i.prop == 'password')
      // const rName = this.userDialogConfig.find((i) => i.prop == 'roleName')
      // this.$set(rName, 'disabled', !!$id)
      // this.$set(psd, 'rules', !$id ? rule : [])
    },
    handleAuthDialogClose() {},
    // 提交表单
    async handleUserSubmit() {
      try {
        // 先进行表单验证
        await this.$refs.userEdit.validate()
        this.userDialogData.roleKey = this.userDialogData.roleName

        // 准备要提交的数据
        const submitData = { ...this.userDialogData }

        let response
        if (this.userDialogType === '新增') {
          // 调用新增角色的API
          response = await addRole(submitData)
          if (response.code !== 200) {
            this.$message.error(response.msg)
            return
          }
          this.$message.success('角色新增成功！')
          console.log(submitData)
        } else if (this.userDialogType === '编辑') {
          await this.$confirm(`编辑保存后，关联的帐号角色将同步修改，确定保存吗?`, '保存', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })

          // 用户点击确认后调用更新角色的API
          response = await updateRole(submitData)
          if (response.code !== 200) {
            this.$message.error(response.msg)
            return
          }
          this.$message.success('角色编辑成功！')
          console.log(submitData)
        }

        // 关闭对话框并刷新表格数据
        this.handleUserDialogClose()
        this.getTableData()
      } catch (error) {
        console.error(`${this.userDialogType}角色失败:`, error)
        // this.$message.error(`${this.userDialogType}角色失败，请检查表单数据！`)
        console.log('提交的数据:', this.userDialogData, this.selectValue)
      }
    },

    handleAuthSubmit() {},
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    getTableData() {
      const params = {
        pageNum: this.pages.pageNum,
        pageSize: this.pages.pageSize,
        ...this.queryParams
      }

      listRole(params).then((res) => {
        this.tableData = res.rows.map((user) => {
          let statusText = ''
          if (user.status === '0') {
            statusText = '生效'
          } else if (user.status === '1') {
            statusText = '失效'
          } else if (user.status === '2') {
            statusText = '休眠'
          }
          // 根据 belongSystem 值设置对应的系统名称
          let belongSystemName = ''
          switch (user.belongSystem) {
            case '0':
              belongSystemName = 'CRM'
              break
            case '1':
              belongSystemName = '劳保'
              break
            case '2':
              belongSystemName = '系统设置'
              break
            default:
              belongSystemName = ''
              break
          }

          return {
            ...user,
            statusText,
            belongSystemName
          }
        })
        this.pages.total = res.total
      })
    },

    // 获取系统对应的角色列表
    async getMenuTree(belongSystem) {
      if (!belongSystem) return
      if (this.isFetchingMenu) return
      this.isFetchingMenu = true

      try {
        const response = await treeselect({ belongSystem })
        this.menuOptions = response.data
      } catch (error) {
        console.error('获取角色列表失败:', error)
      } finally {
        this.isFetchingMenu = false
      }
    },
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      const checkedKeys = this.$refs.menu.getCheckedKeys()
      // 半选中的菜单节点
      const halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys()
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
      return checkedKeys
    },
    handleTreeCheckChange(data, checked, indeterminate) {
      const menuIds = this.getMenuAllCheckedKeys()
      if (checked) {
        if (!this.userDialogData.menuIds.includes(data.id)) {
          this.userDialogData.menuIds = menuIds
        }
      } else {
        this.userDialogData.menuIds = menuIds
      }
    },
    getCheckedNodes(leafOnly, includeHalfChecked) {
      console.log(leafOnly, includeHalfChecked)
    },

    addPidToMenu(menuList, parentId) {
      return menuList.map((item) => {
        const newItem = {
          ...item,
          pid: parentId // 设置当前项的 pid
        }

        // 如果有子节点，递归处理
        if (item.children && item.children.length > 0) {
          newItem.children = this.addPidToMenu(item.children, item.id) // 传递当前项的 id 作为子节点的 pid
        }

        return newItem
      })
    },

    getAllSelectedIds(data) {
      let ids = []
      data.forEach((item) => {
        ids.push(item.id)
        if (item.children && item.children.length > 0) {
          ids = ids.concat(this.getAllSelectedIds(item.children)) // 递归获取子菜单 ID
        }
      })
      return ids
    },

    handleEdit() {},
    handleDelete() {}
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__body .container {
  padding-top: 15px;
  // padding: 20px 0;
  .el-form-item {
    padding: 0;
  }
}
.table-container {
  .header {
    padding: 20px;
  }
  .tabs {
  }

  .dialog-footer {
    display: flex;
    justify-content: right;
    .button {
      width: 100px;
    }
  }
  .roleTree {
    display: flex;
  }
  .m_96 {
    margin: 20px 0;
  }
  .title {
    margin-bottom: 20px;
    font-size: 15px;
    font-weight: 700;
  }

  ::v-deep .el-form-item {
    display: flex;
    align-items: center;
    .el-form-item__label {
      padding: 0 10px;
      width: 90px;
      height: auto;
    }
    .el-range-separator {
      line-height: normal;
      display: flex;
      align-items: center;
    }
    .el-input__icon {
      line-height: normal;
    }
    .el-form-item__content {
      flex: 1;
    }
    .el-input--suffix .el-input__inner {
      width: 100%;
    }
  }
}
</style>
